package com.oracle.malldemo.dao.impl;

import com.oracle.malldemo.dao.AddressDao;
import com.oracle.malldemo.domain.Address;
import com.oracle.malldemo.util.DruidDBUtil;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class AddressDaoImpl implements AddressDao {
    @Override
    public boolean add(Address address) {
        String sql = "insert into address (uid,realname,mobile,province,city,zone,street) values (?,?,?,?,?,?,?);";
        List<Object> argsList = new ArrayList<Object>();
        argsList.add(address.getUid());
        argsList.add(address.getRealname());
        argsList.add(address.getMobile());
        argsList.add(address.getProvince());
        argsList.add(address.getCity());
        argsList.add(address.getZone());
        argsList.add(address.getStreet());

        try{
            DruidDBUtil.startTransaction();
            int result =  DruidDBUtil.executeUpdate(sql,argsList);
            DruidDBUtil.commit();
            DruidDBUtil.endTransaction();
            return true;
        }catch(Exception ex){
            ex.printStackTrace();
            DruidDBUtil.rollback();
            DruidDBUtil.commit();
            DruidDBUtil.endTransaction();
            return true;
        }finally{
            DruidDBUtil.closeAll();
        }

    }

    @Override
    public List<Address> queryAddressListByUid(Integer uid) {

        String sql = "select * from address where uid = ?;";
        List<Object> argsList = new ArrayList<Object>();
        argsList.add(uid);
        List<Address> addressList = new ArrayList<Address>();
        ResultSet rs = null;
        try{
            rs = DruidDBUtil.executeQuery(sql,argsList);
            while(rs.next()){
                Address address = new Address();
                address.setAid(rs.getInt("aid"));
                address.setUid(rs.getInt("uid"));
                address.setRealname(rs.getString("realname"));
                address.setProvince(rs.getString("province"));
                address.setCity(rs.getString("city"));
                address.setMobile(rs.getString("mobile"));
                address.setZone(rs.getString("zone"));
                address.setStreet(rs.getString("street"));
                addressList.add(address);
            }
            return addressList;
        }catch(Exception ex){
            ex.printStackTrace();
            return addressList;
        }finally{
            DruidDBUtil.closeAll();
        }
    }
}
